# Initial process that execs /init.
# This code runs in user space.

#include "include/sysnum.h"

# exec(init, argv)
.global start
start:
	li a0, 2
	li a1, 1
	li a2, 0
	li a7, SYS_dev
	ecall	# dev(O_RDWR, CONSOLE, 0);
	
	li a0, 0
	li a7, SYS_dup
	ecall	# dup(0);  // stdout

	li a0, 0
	li a7, SYS_dup
	ecall	# dup(0);  // stderr

test_brk:
	li a7, SYS_fork
	ecall
	bne a0, zero, test_openat
	la a0, brk
	la a1, argv
	li a7, SYS_exec
	ecall


test_openat:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_mkdirat
	la a0, openat
	la a1, argv
	li a7, SYS_exec
	ecall

test_mkdirat:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_getcwd
	la a0, mkdirat
	la a1, argv
	li a7, SYS_exec
	ecall

test_getcwd:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_getpid
	la a0, getcwd
	la a1, argv
	li a7, SYS_exec
	ecall

test_getpid:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_getppid
	la a0, getpid
	la a1, argv
	li a7, SYS_exec
	ecall

test_getppid:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_dup
	la a0, getppid
	la a1, argv
	li a7, SYS_exec
	ecall

test_dup:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_dup3
	la a0, dup
	la a1, argv
	li a7, SYS_exec
	ecall

test_dup3:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_read
	la a0, dup3
	la a1, argv
	li a7, SYS_exec
	ecall

test_read:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_write
	la a0, read
	la a1, argv
	li a7, SYS_exec
	ecall

test_write:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_chdir
	la a0, write
	la a1, argv
	li a7, SYS_exec
	ecall

test_chdir:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_close
	la a0, chdir
	la a1, argv
	li a7, SYS_exec
	ecall

test_close:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_clone
	la a0, close
	la a1, argv
	li a7, SYS_exec
	ecall



test_clone:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_wait
	la a0, clone
	la a1, argv
	li a7, SYS_exec
	ecall
	
test_wait:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, test_exit
	la a0, wait
	la a1, argv
	li a7, SYS_exec
	ecall

test_exit:
	li a0, 0
	li a7, SYS_wait
	ecall
	li a7, SYS_fork
	ecall
	bne a0, zero, end
	la a0, exit
	la a1, argv
	li a7, SYS_exec
	ecall

# for(;;) exit()
end:
	li a7,SYS_exit
	ecall
	jal end
brk:
	.string "/brk\0"
openat:
	.string "/openat\0"
mkdirat:
	.string "/mkdir_\0"
getcwd:
	.string "/getcwd\0"
getpid:
	.string "/getpid\0"
getppid:
	.string "/getppid\0"
dup:
	.string "/dup\0"
dup3:
	.string "/dup2\0"
read:
	.string "/read\0"
write:
	.string "/write\0"
close:
	.string "/close\0"
exit:
	.string "/exit\0"
chdir:
	.string "/chdir\0"
clone:
	.string "/clone\0"
wait:
	.string "/wait\0"
.p2align 2
argv:
	.long 0
